import Vuex from 'vuex'
import Vue from 'vue'
import * as type from '../../mutation-types'

Vue.use(Vuex) // 使用Vuex插件

const moduleA = {
  state: {
    name: 'moduleA',
    username: 'cuifan'
  },
  mutations: {
    [type.TEST_MODULEA](state, payload) {

    }
  },
  actions: {
    [type.TEST_MODULEA]({ state, commit, getters, rootGetters }) {
      setTimeout(function() {
        state.username = 'simon'
        commit(type.TEST_MODULEA)
      }, 2000)
      console.log(getters === rootGetters);
    }
  },
  getters: {
    getUsername(obj) {
      // console.log(obj);
    }
  }
}

const store = new Vuex.Store({
  state: {
    count: 100,
    number: 100,
    info: 'hello world',
    sNum: 0,
    obj: { title: 'hello world' },
    students: [{
      id: 100,
      name: 'cuifan',
      age: 20,
    }, {
      id: 101,
      name: 'cuifan1',
      age: 21,
    }, {
      id: 106,
      name: 'cuifan2',
      age: 22,
    }, {
      id: 105,
      name: 'cuifan3',
      age: 18,
    }, {
      id: 103,
      name: 'cuifan4',
      age: 22,
    }, {
      id: 104,
      name: 'cuifan5',
      age: 15,
    }]
  },
  mutations: {
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    },
    getParams(state, payload) {
      console.log(payload);
    },
    getParams1(state, payload) {
      console.log(payload);
    },
    numberChange(state, payload) {
      // state.obj.number = payload.num
      state.obj.title = 'hello cuifan'
        // 往state中添加属性的时候不是响应式的
        // 用Vue.set(对象，属性名，属性值)来添加
        // Vue.set(state.obj, 'number', payload.num)
      state.obj = {...state.obj, number: payload.num }
    },
    [type.TEST_MUTATION](state, payload) {
      state.info = 'hello cuifan'
      console.log(payload);
    },
    [type.TEST_AYNC](state, payload) {
      // 进行异步操作的话vuex追踪不到
      setTimeout(function() {
        console.log(payload);
        state.sNum += payload.sNumber
      }, 2000)
    },
    [type.TEST_ACTION](state, payload) {
      console.log(payload);
    },

  },
  actions: {
    [type.TEST_ACTION](context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(function() {
          context.state.sNum += payload.sNumber
          context.commit(type.TEST_ACTION, payload)
          resolve(123)
        }, 2000)
      })
    }
  },
  getters: {
    studentsThan20(state) {
      return state.students.filter(student => {
        return student.age > 20
      }).sort((x, y) => {
        return x.id - y.id
      })
    },
    studentsThan20Len(state, getters) {
      return getters.studentsThan20.length
    },
    studentGettedById(state, getters) {
      return id => {
        return state.students.find(student => {
          return student.id === id
        })
      }
    }
  },
  modules: {
    moduleA
  }
})

export default store